import React, { useState, useRef, useEffect,useImperativeHandle } from "react";


export const InputFocus: React.FC = () => {

    const inputRef = useRef<HTMLInputElement>(null)

    const getFocus = () => {
        inputRef.current?.focus()
    }

    return (
        <>
            <input type="text" ref={inputRef} />
            <br />
            <button onClick={getFocus}>获取焦点</button>
        </>
    )
}



export const Counter: React.FC = () => {

    const [count, setCount] = useState(0)

    // useRef仅在函数第一次调用时执行，重新调用渲染时组件时，不会再次执行
    const prevCount = useRef<number>(0)

    const add = () => {
        setCount((prev) => {
            prevCount.current = prev
            return prev + 1
        })
    }
    return (
        <div>
            <h1>count的新值是：{count}，旧值是：{prevCount.current}</h1>
            <br />
            <button onClick={add}>+1</button>
        </div>
    )
}



export const RefTimer: React.FC = () => {
    const [count, setCount] = useState(0)

    const refTime = useRef<number>(Date.now())

    const changeCount = () => {
        // 变化能更新渲染
        setCount(prev => prev + 1)
    }

    const changeTime = () => {
        //变化并不能更新渲染
        refTime.current = Date.now()
        console.log(refTime.current)
    }


    // 1.useEffect 会在组件首次渲染完毕之后，默认执行一次
    // 2.组件每次渲染完毕之后，会触发useEffect的回调函数，如果给了依赖项数组，则还要判断依赖项是否变化，再决定能否触发函数
    useEffect(() => {
        console.log("触发了useEffect的回调执行")
    }, [refTime.current])

    return (
        <>
            <h1>count的值是：{count}</h1>
            <h1>refTime当前的值是：{refTime.current}</h1>
            <button onClick={changeCount}>更改count</button>
            <button onClick={changeTime}>更改refTime</button>
        </>
    )
}



const Child =  React.forwardRef((_,ref) => {

    const [count, setCount] = useState(0)

    const add = (num:number)=>{
       setCount(prev=>prev += num)
    }

    useImperativeHandle(ref,()=>{
        // 暴露count，setCount
        return {
            count,
            setCount
        }
    },[count])

    return (
        <>
            <h2>子组件的count值是：{count}</h2>
            <button onClick={()=>add(1)}>+1</button>
            <button onClick={()=>add(-1)}>-1</button>
        </>
    )
})


interface ChildRefMessage {
    count:number,
    setCount:(value:number)=>void
}

export const Father: React.FC = () => {
    const childRef = useRef<ChildRefMessage | null>(null)

    // 打印子组件信息
    const showMessage = ()=>{
       console.log(childRef.current)
    }
    // 重置子组件信息
    const resetChild = ()=>{
        childRef.current?.setCount(0)
    } 
    return (
        <>
            <h1>这是父组件</h1>
            <button  onClick={showMessage}>获取子组件信息</button>
            <button onClick={resetChild}>重置</button>
            <hr />
            <Child ref={childRef} />
        </>
    )
}

